import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PLATFORM_COLOR = (150, 75, 0)

# 设置游戏窗口，按照 iPhone 14 比例调整
screen_width = 390  # 等比例缩小
screen_height = 844  # 等比例缩小
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Go Downstairs")

# 玩家初始位置和大小
player_x = screen_width // 2 - 25
# 将玩家初始位置调整到屏幕中间靠下
player_y = screen_height * 3 // 4
player_width = 50
player_height = 50
player_vel = 5
player_fall_speed = 3
player_fall_acceleration = 0.1

# 平台设置
platform_width = 100
platform_height = 10
# 台阶高度差至少为小方块高度的两倍
platform_gap = player_height * 2  
# 计算一个屏幕能容纳的台阶数量
num_platforms = screen_height // platform_gap + 1
platform_list = []
for i in range(num_platforms):
    platform_x = random.randint(0, screen_width - platform_width)
    platform_y = screen_height - i * platform_gap
    platform_list.append(pygame.Rect(platform_x, platform_y, platform_width, platform_height))

# 画面滚动速度
scroll_speed = 3

# 游戏主循环
running = True
clock = pygame.time.Clock()

while running:
    screen.fill(WHITE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a] and player_x > 0:
        player_x -= player_vel
    if keys[pygame.K_d] and player_x < screen_width - player_width:
        player_x += player_vel

    # 玩家下落逻辑
    landed = False
    player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
    for platform in platform_list:
        # 调整碰撞检测逻辑
        if player_rect.colliderect(platform) and player_fall_speed > 0:
            player_y = platform.y - player_height
            player_fall_speed = 3
            landed = True
            break

    if not landed:
        player_fall_speed += player_fall_acceleration
        player_y += player_fall_speed

    # 检查游戏结束条件
    if player_y > screen_height or player_y + player_height < 0:  # 添加小方块被画面上方淹没的结束条件
        running = False

    # 移动平台和画面
    new_platform_list = []
    for platform in platform_list:
        platform.y -= scroll_speed  # 平台向上移动
        if platform.y + platform_height > 0:
            new_platform_list.append(platform)
    platform_list = new_platform_list

    # 生成新平台
    # 当最上面的平台快移出屏幕时生成新台阶
    if platform_list and platform_list[0].y < screen_height:
        platform_x = random.randint(0, screen_width - platform_width)
        platform_y = platform_list[-1].y + platform_gap
        platform_list.append(pygame.Rect(platform_x, platform_y, platform_width, platform_height))

    # 绘制平台
    for platform in platform_list:
        pygame.draw.rect(screen, PLATFORM_COLOR, platform)

    # 绘制玩家
    pygame.draw.rect(screen, BLACK, (player_x, player_y, player_width, player_height))

    pygame.display.update()
    clock.tick(60)

pygame.quit()